package com.loanapp.server.market.provider.modular.home.service.impl;


import com.loanapp.base.common.utils.DoubleUtil;
import com.loanapp.base.common.utils.StringUtil;
import com.loanapp.base.database.common.base.SqlMapper;
import com.loanapp.server.market.api.platform.entity.CmsChannel;
import com.loanapp.server.market.api.platform.entity.CmsContent;
import com.loanapp.server.market.provider.modular.home.service.MainIndexService;
import com.loanapp.server.market.provider.modular.platform.mapper.CmsChannelMapper;
import com.loanapp.server.market.provider.modular.platform.mapper.CmsContentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Desc:
 * Author: dushuang
 * Date: Create in 2017/8/24
 */
@Service
public class MainIndexServiceImpl implements MainIndexService {

    @Autowired
    private CmsChannelMapper cmsChannelMapper;

    @Autowired
    private CmsContentMapper cmsContentMapper;

    @Autowired
    private SqlMapper sqlMapper;

    @Value(value = "${app.downloadUrl}")
    private String appDownLoadUrl;

    private List<CmsContent> getContentList(String channelId) {
        Example example = new Example(CmsContent.class);
        example.createCriteria().andEqualTo("channelId", channelId);// 栏目ID
        example.createCriteria().andEqualTo("status", 1);   // 状态(1显示)
        example.setOrderByClause(" create_time desc ");
        List<CmsContent> contentList = cmsContentMapper.selectByExample(example);
        return contentList;
    }

    /**
     * 首页bannar
     *
     */
    @Override
    public List<Map<String, Object>> getBannar(String channelId) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("a.id,a.title_img AS titleImg,a.url ");
        sql.append("FROM cms_content a ");
        sql.append("WHERE 1=1 ");
        sql.append("AND a.`status` = 1 ");
        sql.append("AND a.channel_id = '"+channelId+"' ");
        return sqlMapper.selectList(sql.toString());
    }

    @Override
    public List<Map<String, Object>> getStarProduct(String productType) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("p.id, ");
        sql.append("p.product_img, ");
        sql.append("p.product_name, ");
        sql.append("p.min_quato, ");
        sql.append("p.max_quato, ");
        sql.append("p.lend_speed, ");
        sql.append("IFNULL(p.daily_interest_rate,0)*30 as daily_interest_rate ");
        sql.append("FROM platform_product_extra pe ");
        sql.append("LEFT JOIN platform_product_info p ON pe.product_id = p.id ");
        sql.append("WHERE pe.product_type = '"+productType+"' ");
        sql.append("AND p.status = 1  ");
        List<Map<String, Object>> applyList = sqlMapper.selectList(sql.toString());
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map<String, Object> map : applyList) {
            map.put("id", Integer.valueOf(map.get("id") + ""));
            map.put("product_name", StringUtil.toString(map.get("product_name")));// 公司名称
            map.put("product_img", StringUtil.toString(map.get("product_img")));// logo
            map.put("lend_speed", StringUtil.toString(map.get("lend_speed"))+"小时");//  放款速度
            map.put("daily_interest_rate", StringUtil.toString(map.get("daily_interest_rate")));// 日利息
            map.put("quato",
                    getQuato(StringUtil.toString(map.get("min_quato")), StringUtil.toString(map.get("max_quato"))));// 放款额度
            // 查询标签
            map.remove("min_quato");
            map.remove("max_quato");
            result.add(map);
        }
        return result;
    }

    private String getQuato(String minQuato, String maxQuato) {
        String quato = "";
        if (!StringUtil.isEmpty(minQuato)) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato));
        }
        if (!StringUtil.isEmpty(maxQuato)&&!maxQuato.equals("0.00")) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
        }
        if (!StringUtil.isEmpty(minQuato) && !StringUtil.isEmpty(maxQuato)&&!maxQuato.equals("0.00")) {
            quato = DoubleUtil.toZeroDecimal(Double.valueOf(minQuato)) + "~"
                    + DoubleUtil.toZeroDecimal(Double.valueOf(maxQuato));
        }
        return quato;
    }

    @Override
    public List<Map<String, Object>> getBorrowRecord() {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("CONCAT('尾号',SUBSTR(phone,-4,4),'用户在[',p.product_name,']成功申请 ¥ ',IF(max_quato = 0,min_quato,max_quato)) AS note, ");
        sql.append("SUBSTR(phone,-4,4) AS phone, ");
        sql.append("p.product_name, ");
//        sql.append("expected_amount, ");
        sql.append("IF(max_quato = 0,min_quato,max_quato) as money ");
        sql.append("FROM customer_borrow_info cb  ");
        sql.append("LEFT JOIN platform_product_info p ON cb.product_id = p.id ");
        sql.append("WHERE 1=1 ");
        sql.append("AND phone IS NOT NULL AND phone <> '' ");
        sql.append("AND product_id IS NOT NULL ");
        sql.append("ORDER BY RAND() DESC ");
        sql.append("LIMIT 100 ");
        return sqlMapper.selectList(sql.toString());
    }

    @Override
    public List<Map<String, Object>> getIndexNews(String cmsChannel) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("a.id, ");
        sql.append("a.url, ");
        sql.append("a.title, ");
        sql.append("a.title_img as img ");
        sql.append("FROM cms_content a ");
        sql.append("WHERE 1=1 ");
        sql.append("AND a.`status` = 1 ");      // 内容是启用状态
        sql.append("AND a.show_app_index = 1 ");    // 页面显示
        sql.append("AND a.channel_id IN ("+cmsChannel+") ");
        sql.append("ORDER BY a.create_time DESC ");
        return sqlMapper.selectList(sql.toString());
    }

    @Override
    public List<Map<String, Object>> getActivity(String cmsChannel) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("a.id, ");
        sql.append("a.url, ");
        sql.append("a.title, ");
        sql.append("a.title_img as img ");
        sql.append("FROM cms_content a ");
        sql.append("WHERE 1=1 ");
        sql.append("AND a.`status` = 1 ");      // 内容是启用状态
        sql.append("AND a.channel_id = '"+cmsChannel+"' ");
        return sqlMapper.selectList(sql.toString());
    }

    @Override
    public Map<String, Object> getCmsDesc(String cmsId) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT ");
        sql.append("a.id, ");
        sql.append("a.channel_id AS channelId, ");
        sql.append("a.title, ");
        sql.append("a.title_img AS titleImg, ");
        sql.append("a.url, ");
        sql.append("b.`name` AS author, ");
        sql.append("a.detail, ");
        sql.append("a.create_time AS createTime ");
        sql.append("FROM cms_content a ");
        sql.append("LEFT JOIN `user` b ON a.author = b.id ");
        sql.append("WHERE 1=1 ");
        sql.append("AND a.`status` = 1 ");
        sql.append("AND a.id = '" + cmsId + "' ");
//        CmsContent condition = new CmsContent();
//        condition.setId(Long.valueOf(cmsId));
//        condition.setStatus(1);
//        CmsContent cmsContent = cmsContentMapper.selectOne(condition);
        List<Map<String, Object>> result = sqlMapper.selectList(sql.toString());
        return result.size()>0?result.get(0):null;
    }

    @Override
    public Map<String, Object> findAppDetail(String versionId, String storeNameChannel) {
        StringBuilder sBuffer = new StringBuilder();
        sBuffer.append("SELECT	id,	app_type appType,app_version appVersion,update_content as updateContent,  ");
        sBuffer.append("update_time updateTime,need_update needUpdate,size,file_MD5 ");
        sBuffer.append("FROM app_version where 1=1 ");
        if (StringUtil.isNotEmpty(versionId)) {
            sBuffer.append("and id =" + versionId);
        }
        Map<String, Object> map = sqlMapper.selectOne(sBuffer.toString());

        if (StringUtil.isNotEmpty(storeNameChannel)) {
            String sqlLink = "SELECT link FROM app_market  WHERE market_name ='" + storeNameChannel + "'";
            String link = sqlMapper.selectOne(sqlLink, String.class);
            if (StringUtil.isEmpty(link)) {
                map.put("apkDownPath", appDownLoadUrl);
            } else {
                map.put("apkDownPath", link);
            }
        } else {
            map.put("apkDownPath", appDownLoadUrl);
        }
        return map;
    }

    /**
     * 帮助中心
     *
     */
    @Override
    public List<Map<String, Object>> getHelpCenter(String channelId) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Example example = new Example(CmsChannel.class);
        example.createCriteria().andEqualTo("parentId", channelId);// 父栏目ID
        example.setOrderByClause(" priority asc ");// 排序
        List<CmsChannel> channelList = cmsChannelMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(channelList)) {
            for (CmsChannel channel : channelList) {
                Map<String, Object> channelMap = new HashMap<String, Object>();
                List<CmsContent> contentList = getContentList(StringUtil.toString(channel.getId()));
                List<Map<String, Object>> tmpList = new ArrayList<Map<String, Object>>();
                if (!CollectionUtils.isEmpty(contentList)) {
                    for (CmsContent cms : contentList) {
                        Map<String, Object> contentMap = new HashMap<String, Object>();
                        contentMap.put("title", cms.getTitle());// 标题
                        contentMap.put("detail", cms.getDetail());// 详情
                        tmpList.add(contentMap);
                    }
                    channelMap.put("channel", channel.getChannelName());
                    channelMap.put("contentList", tmpList);
                    list.add(channelMap);
                }
            }
        }
        return list;
    }
}
